define(['moment'], function (moment) {
    return ['$rootScope', '$scope', '$filter', '$stateParams', 'config', 'MMWService', '$timeout',
        function ($rootScope, $scope, $filter, $stateParams, config, $MMWService, $timeout) {
            $scope.init = function(){
                var _SMT21init = localStorage.getItem(config.appName + '_SMT21_init');
                if(_SMT21init){
                    $scope.data = JSON.parse(_SMT21init);
                    $scope.data_counting={};
                    $scope.data_counting.total_list_num = 0;
                    $scope.data_counting.total_fullbox_num = 0;
                    $scope.data_counting.remain_num = $scope.data.levelqty;
                    $scope.box_level = "middle";//預設箱數等於小箱。
                } else{
                    $scope.data = {
                        type:0,
                        mode:0,
                        area_no: '',
                        op_no: '',
                        source: '',
                        level_name:''
                    };

                    $scope.data_counting = {
                        total_list_num:0,
                        remain_num:'',
                        total_fullbox_num:0
                    }
                }
                $scope.packing_list = [];
                $scope.item_list = [];
                $scope.packing_content=[];//用來包很多箱號的陣列
                $scope.packing_detail=[];//一箱內的內容物
                $scope.barcode_no='';
            };

            // barcode輸入
            $scope.input_barcode_no = function(event){
                let barcode = $scope.barcode_no;
                if(event.keyCode == 13){
                    $scope.search(barcode);
                }
            };

            $scope.back = function(){
                $scope.$root.hideMenu();
                $scope.$root.changeProgram('home', true);
            };

            $scope.cleanAll = function(){//清除
                $scope.product_no='';
                $scope.product_name = '';//產品名稱清除
                $scope.item_spec = '';//產品規格data
                $scope.packing_detail=[];
                $scope.data_counting.remain_num=$scope.data.levelqty;
                $scope.data_counting.total_list_num=0;

            }

            // 選擇區域 (開窗)
            $scope.loadAreaList = function () {
                $MMWService.showQueryListPNIG({
    				page_mode: 'smt_std_area_info_get',
                    key: 'areano',
                    header: [
                        {label:$filter('translate')('common.queryList.area_c'), code:'areano'},
                        {label:$filter('translate')('common.queryList.area_n'), code:'areaname'}
                    ],
                    confirm:function(selectItem, dialog){
                        dialog.hide();
                        $scope.data.area_no = selectItem.areano;
                        $scope.data.op_no = '';
                        $scope.data.source = '';
                        $scope.data.level_name = '';
                        $scope.loadOpNoList();
                    }
                });
            };

            // 選擇作業站 (開窗)
            $scope.loadOpNoList = function () {
                if($scope.area_no != ''){
                    $MMWService.showQueryListPNIG({
                        page_mode:'smt_std_area_op_info_get',
                        key: 'opno',
                        header: [
                            {label:$filter('translate')('common.queryList.op_c'), code:'opno'},
                            {label:$filter('translate')('common.queryList.op_n'), code:'opname'}
                        ],
                        setCondition: function (conditions) {
                            conditions.push({ column_name: 'b.AREANO', query_mode: '0', value: $scope.data.area_no, merge_condition_model: 'AND' });
                            return conditions;
                        },
                        confirm:function(selectItem, dialog){
                            dialog.hide();
                            $scope.data.op_no = selectItem.opno;
                            $scope.data.source = '';
                            $scope.data.level_name = '';
                            $scope.loadsourceList();
                        }
                    });
                }
            };

            // 選擇包裝來源 (開窗)
            $scope.loadsourceList = function () {
                if($scope.area_no != ''){
                    $MMWService.showQueryListPNIG({
                        page_mode:'smt_source_info_get',
                        key: 'productno',
                        header: [
                            {label:$filter('translate')('SMT21.plot_no'), code:'lotno'},
                            {label:$filter('translate')('SMT21.product_no'), code:'productno'},
                            {label:$filter('translate')('SMT21.product_name'), code:'productname'}
                        ],
                        setCondition: function (conditions) {
                            conditions.push({ column_name: 'b.AREANO', query_mode: '0', value: $scope.data.area_no, merge_condition_model: 'AND' });
                            conditions.push({ column_name: 'a.OPNO', query_mode: '0', value: $scope.data.op_no, merge_condition_model: 'AND' });
                            return conditions;
                        },
                        confirm:function(selectItem, dialog){
                            dialog.hide();
                            $scope.data.lotno = selectItem.lotno;
                            $scope.data.productno = selectItem.productno;
                            $scope.data.productversion = selectItem.productversion;
                            $scope.loadlevelNameList();
                        }
                    });
                }
            }

            //選擇包裝階層
            $scope.loadlevelNameList = function () {
                if($scope.area_no != ''){
                    $MMWService.showQueryListPNIG({
                        page_mode:'smt_packing_level_info_get',
                        key: 'levelname',
                        order:'packlevelseq',//加上order就能按變數排序。
                        header: [
                            {label:$filter('translate')('SMT21.packlevelseq'), code:'packlevelseq'},
                            {label:$filter('translate')('SMT21.levelname'), code:'levelname'},
                            {label:$filter('translate')('SMT21.levelqty'), code:'levelqty'},
                            {label:$filter('translate')('SMT21.leveldescription'), code:'leveldescription'},
                        ],
                        setCondition: function (conditions) {
                            conditions.push({ column_name: 'a.ProductNo', query_mode: '0', value: $scope.data.productno, merge_condition_model: 'AND' });
                            conditions.push({ column_name: 'a.ProductVersion', query_mode: '0', value: $scope.data.productversion, merge_condition_model: 'AND' });
                            return conditions;
                        },
                        confirm:function(selectItem, dialog){
                            dialog.hide();
                            $scope.data.packlevelseq = selectItem.packlevelseq;//包裝序
                            $scope.data.level_name = selectItem.levelname;//包裝名稱
                            $scope.data.levelqty = selectItem.levelqty;//包裝數
                            $scope.data_counting.remain_num = selectItem.levelqty//剩餘數
                            $scope.data.packlevelguid = selectItem.packlevelguid;//取箱號時會用到的guid
                            $scope.data.content=selectItem.content;
                        }
                    });
                }
            }

            //改變panel大小
            $scope.changePanelSize = function(size_type){
                if($scope.packing_panel_mode == undefined){
                    $scope.packing_panel_mode = size_type;
                } else {
                    $scope.packing_panel_mode = undefined;
                }
            }

            //進入過帳畫面
            $scope.confirm = function(){
                if($scope.page_mode !== 'next_page'){
                    if($scope.data.level_name){
                      $scope.page_mode = 'next_page';
                      localStorage.setItem(config.appName + '_SMT21_init', JSON.stringify($scope.data));
                      $scope.data_counting.total_fullbox_num=0;
                    }else{
                        $scope.$root.showAlert($filter('translate')('SMT21.msg.select_level_name_plz'));
                    }
                }
            }

            function stdpacking_generate_box_process(){
                if($scope.packing_detail.length > 0 ){
                    $MMWService.sendToServer({//呼叫箱數服務
                        uri:'ServicesSMT.Module_SMT.stdpacking_generate_box_process',
                        content : {
                            lot_no:$scope.data.lotno,
                            guid:$scope.data.packlevelguid
                        },
                        success: function(data){
                            if(data!=''){
                                if($scope.data_counting.remain_num!=0){
                                    $scope.$root.showConfirm($filter('translate')('SMT20.msg.this_box_not_full',{total_num:$scope.data_counting.total_list_num, box_no:data.box_no}), function(confirmDialog){ 
                                        confirmDialog.hide();
                                        $scope.save_and_print(data);
                                    }); 
                                }else{
                                    $scope.$root.showConfirm($filter('translate')('SMT20.msg.this_box_has_been_full',{total_num:$scope.data_counting.total_list_num, box_no:data.box_no}), function(confirmDialog){
                                        confirmDialog.hide();
                                        $scope.save_and_print(data);
                                    }); 
                                }
                            }else{
                                $scope.$root.showAlert( $filter('translate')('SMT20.msg.box_no_has_no_data'))
                            }
                        }
                    });  
                }else{
                    $scope.$root.showAlert( $filter('translate')('SMT20.msg.packing_detail_no_data'));
                }
            }

            $scope.sealBox = function(){//強制封箱
                if($scope.isCheckOk == 1){
                    $rootScope.showConfirm($filter('translate')('SMT21.msg.box_unqualified'),function(dialog){
                        stdpacking_generate_box_process();
                        dialog.hide();
                    })
                }else{
                    stdpacking_generate_box_process()
                }
            }

            $scope.select_package = function(item){
                item.isSelect= !item.isSelect;
            }

            //存檔並列印
            $scope.save_and_print=function(info){
                let content={
                    packing_content:[{
                        packing_sn:info.box_no,
                        print_times:0,
                        only_print:'false',
                        total_num:$scope.data_counting.total_list_num,
                        isSelect:false,
                        ip: config.server.ip,
                        port: config.server.port,
                        packing_detail:$scope.packing_detail,
                        pack_level:$scope.data.packlevelseq,                            
                        guid:$scope.data.packlevelguid,
                        create_max_detail:info.create_max_detail
                    }]
                }
                $scope.packing_list.unshift(content.packing_content[0]);//將左邊資料拋至右邊
                $scope.data_counting.total_fullbox_num = $scope.packing_list.length;//單位數跟著右邊項目數量變動
                $MMWService.sendToServer({
                    uri:'ServicesSMT.Module_SMT.stdpacking_save_process',
                    content : content,
                    success: function(data){
                        printTag(data.pcs_detail,0);
                        let double_print = $scope.packing_detail;
                        $scope.packing_detail=[];
                        $scope.product_no='';//產品編號清除
                        $scope.product_ver = '';//產品編號清除
                        $scope.product_name = '';//產品名稱清除
                        $scope.item_spec = '';//產品規格data
                        //托盤數、裝箱數復原
                        $scope.data_counting.total_tray_num=0;
                        $scope.data_counting.total_list_num=0;
                        $scope.data_counting.remain_num=$scope.data.levelqty;
                        
                    }
                });
            }

            $scope.printTag_one_more_time=function(){
                let printArr = $scope.packing_list.filter(function(item){
                    return item.isSelect === true;
                });

                printArr.forEach(function(item){
                    item.only_print="true";
                })
                let content={
                    packing_content:printArr
                }
                //詢問是否再次列印標籤？
                $MMWService.sendToServer({
                    uri:'ServicesSMT.Module_SMT.stdpacking_save_process',
                    content : content,
                    success: function(data){
                        printTag(data.pcs_detail,0);
                        $scope.packing_list.forEach(function(item){
                            if(item.isSelect===true){
                                item.print_times++;
                            }
                        })
                        $scope.$root.showToast($filter('translate')('SMT21.msg.printag_success'));
                    }
                });
            }

            $scope.removeRow=function(item){
                $scope.packing_detail.splice($scope.packing_detail.indexOf(item),1);
                let j = $scope.packing_detail.length;
                for(var i= 0; i < $scope.packing_detail.length; i++){
                    $scope.packing_detail[i].seq = j;
                    j--;
                }
                $scope.data_counting.total_list_num--;
                $scope.data_counting.remain_num++;
            }
            
            // 進入設定畫面
            $scope.settings = function(){
                $scope.page_mode = '';
                $scope.product_no='';
                $scope.product_name = '';//產品名稱清除
                $scope.item_spec = '';//產品規格data
                $scope.barcode_no='';
                $scope.packing_detail=[];//左邊欄位清空
                $scope.packing_list=[];//右邊欄位清空
            }

            // QRCode輸入
            $scope.QRCodeScanner = function(){
                $scope.$root.OpenScanner({
                    after : function(result){
                        $scope.input_barcode(result.text);
                    },
                    exception: function(){
                        //目前裝置無法使用相機
                        $scope.$root.showAlert($filter('translate')('B0214.showAlert.column3'));
                    },
                    orientation : 'landscape'
                });
            };

            // 查詢
            $scope.input_barcode = function(barcode){
                $MMWService.sendToServer({
                    uri:'ServicesSMT.Module_SMT.panel_info_get',
                    content : {
                        type:$scope.data.type,
                        equipment_no:$scope.data.machine_no,
                        input_no: barcode,
                        panel_side: $scope.data.panel_side,
                        plot_no: $scope.data.plot_no,
                        seq: $scope.data.seq,
                        area_no: $scope.data.area_no,
                        op_no: $scope.data.op_no,
                        posting_source_type: $scope.data.posting_source_type,
                        allow_duplicate_posting: $scope.data.allow_duplicate_posting
                    },
                    success: function(data){
                        if(data.pcs_list && data.pcs_list.length > 0){
                            $scope.data.mode = data.mode;
                            $scope.data.plot_no = data.lot_no;
                            $scope.data.product_no = data.product_no;
                            $scope.data.item_spec = data.item_spec;
                            $scope.data.qty = data.pcs_count;
                            $scope.data.posted_qty = data.posted_qty;
                            //$scope.qty = data.qty;
                            //data.pcs_list.forEach(function(pcs_item, index){
                            for(var i = 0; i < data.pcs_list.length; i++){
                                var pcs_item = data.pcs_list[i];
                                pcs_item.index = $scope.item_list.length;
                                pcs_item.op_no = $scope.data.op_no;
                                pcs_item.plot_no = $scope.data.plot_no;
                                pcs_item.equipment_no = $scope.data.machine_no;
                                $scope.item_list.push(pcs_item);
                                // 20200108 modify by WeiTing for M#66213 - 跟 SA 和 後端 確認過後，拿掉卡控，改成每個加工序刷入的序號都各自獨立進行。
                                // if(pcs_item.status == 'R'){
                                //     pcs_item.status = 'Fail';
                                //     pcs_item.remark = $filter('translate')('SMT17.msg.seq_aready_ng');
                                //     data.pcs_list.splice(i, 1);
                                //     i--;
                                // } else if(pcs_item.status == 'D'){
                                //     pcs_item.status = 'Fail';
                                //     pcs_item.remark = $filter('translate')('SMT17.msg.seq_aready_pass');
                                //     data.pcs_list.splice(i, 1);
                                //     i--;
                                // }
                            };
                            if(data.pcs_list.length > 0){
                                panel_info_set_process(data);
                            }
                        } else {
                            $scope.item_list.push({
                                index:$scope.item_list.length,
                                pcs_no: barcode,
                                panel_no: '',
                                status: 'Fail',
                                remark: $filter('translate')('common.msg.no_data')
                            });
                        }
                    },
                    error: function (data) {
                        $scope.item_list.push({
                            index: $scope.item_list.length,
                            pcs_no: $scope.data.posting_source_type== 1 ? '':barcode,
                            panel_no: $scope.data.posting_source_type == 1 ? barcode : '',
                            status: 'Fail',
                            remark: data.Message
                        });
                    }
                });
            };

            // 查詢
            $scope.search = function(barcode){
                let content={
                    pcs_no:barcode,
                    area_no:$scope.data.area_no,
                    op_no:$scope.data.op_no,
                    pack_level:$scope.data.packlevelseq,
                    lot_no:$scope.data.lotno,
                    product_no:$scope.data.productno,
                    product_ver:$scope.data.productversion,
                    is_first:'false'
                }
                if($scope.packing_detail.length===0){
                    content.is_first="true";
                }
                if(barcode != ''){
                    let no_repeat = true;
                    if($scope.packing_detail.length>0){
                        no_repeat = $scope.packing_detail.every(function(item){
                            return item.pcs_no!=barcode;
                        })
                    }
                    if(no_repeat){//產品序號無重複
                        if((+$scope.data_counting.total_list_num) === (+$scope.data.levelqty)){//判斷是否已滿箱，如以滿箱便不新增產品
                            $scope.$root.showAlert( $filter('translate')('SMT21.msg.box_has_been_full'));
                        }else{
                            $MMWService.sendToServer({
                                uri:'ServicesSMT.Module_SMT.stdpacking_product_info_get',
                                content : content,
                                success: function(data){
                                    if(data!=''){
                                        if($scope.packing_detail.length===0){
                                            $scope.std_product_no = data.product_no;//產品編號
                                            $scope.std_productversion = $scope.data.productversion //產品版本
                                        }else{
                                            if((data.product_no + data.product_ver) != ($scope.std_product_no + $scope.std_productversion)){
                                                $scope.$root.showAlert($filter('translate')('SMT21.msg.different_product_no'))
                                                return;
                                            }
                                        }
                                        $scope.isCheckOk = data.IsCheckOk;//是否已檢驗
                                        $scope.product_no = data.product_no;//產品編號
                                        $scope.product_name = data.product_name;//產品名稱
                                        $scope.item_spec = data.item_spec;//產品規格data
                                        data.seq = $scope.packing_detail.length + 1;
                                        let packing_data={
                                            seq:data.seq,
                                            pcs_no:barcode,
                                            level_qty:1,
                                            lot_no:$scope.data.lotno,
                                        }
                                        $scope.packing_detail.unshift(packing_data); 
                                        // 托盤數、總數、剩餘數計算
                                        $scope.data_counting.total_list_num++;
                                        $scope.data_counting.remain_num--;

                                        if((+$scope.data_counting.total_list_num) === (+$scope.data.levelqty)){
                                            $scope.data_counting.total_fullbox_num++;
                                            $scope.sealBox();
                                        }
                                        $scope.barcode_no='';
                                    }else{
                                        $scope.$root.showAlert( $filter('translate')('common.msg.no_data'));
                                    }
                                }
                            });
                        }
                    }else{
                        $scope.$root.showAlert( $filter('translate')('SMT20.msg.product_no_repeat'));
                        $scope.barcode_no='';
                    }
                }
            };

            function printTag(tags, index){
                if(tags && index < tags.length){
                    if(window.nodeRequire){
                        var exec = window.nodeRequire('child_process').exec;
                        exec(tags[index].commandline, function(error, stdout, stderr){
                            if(error){
                                $rootScope.showAlert($filter('translate')('E01.msg.cantprint'));
                            }
                            index = index +1;
                            printTag(tags, index);
                        });
                    }
                }
            };
        }
    ];
});
